04. Sets
Sets
ND079 C1 L6 A04 Sets
What is a Set?
Sometimes, as with the example of a list of phone numbers, it's important for the values in a collection to be unique. Fortunately, we have Sets. A Set is a collection type that has no duplicate values.
Note that Set extends the Collection interface and therefore provides the same methods as other Collection data structures do.
Concrete Implementations
There are three concrete implementations for the Set interface:
- HashSet
- TreeSet
- LinkedHashSet
Each of these implementations vary, but all of them enforce the no-duplicate-values requirement of the Set interface.
Note: Above, we referred to these as "concrete implementations". Remember, "concrete" means that they are not interfaces or abstract classes, and they contain all of the code necessary per the interface.
Set Syntax
For your reference, here are the syntax examples we just looked at for creating and using sets.
Creating a Set Object
In the Collections framework, the Set is an interface and cannot be directly used to instantiate a class. In the example below we are creating a Set of strings. Notice, we are using the concrete class HashSet to instantiate our Set object.
Set<String> mySet = new HashSet<String>();
Adding to a Set
Next we will look at adding objects to our Set. Remember that a Set has an additional restriction that no duplicate values are allowed. In this example we are adding Strings to our Set using the add
method:
mySet.add("Hello");
mySet.add("Hello");
mySet.add("Hellos");
Even though we used add
three times, this will actually only add two items, since one of the items is a duplicate.
Retrieving an Object From a Set
In this example we will be looking at the syntax to retrieve a String object from our Set. Unfortunately, the only way retrieve an object from a Set is to iterate over the Set looking for the object. Below we are iterating over the Set to look for the "Hello"
String. This example is simple but provides the necessary techniques for finding an object in a Set.
String foundObject;
for (String text : mySet) {
if(text.equals("Hello"){
foundObject = text;
}
}
SOLUTION:
- Sets implement the Collection interface.
- Sets enforce no duplicate values.
- Sets can be populated from another data list that implements the Collection interface.